<?php
namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Response\Json;
use think\Db;
use PHPExcel_IOFactory;
use PHPExcel;

/**
* 前台首页
*/
class Api extends Base
{	
	public function _initialize() {
		parent::_initialize();
	}

	public function search() {
		$request 			= request();
		$params 			= $request->param();

		echo json_encode($params['k'], JSON_UNESCAPED_UNICODE);
		exit;
	}

	public function lists() {
        $request                 = $this->request;
	    $params 		         = $request->param();
	    $p                       = $request->has('p') ? $params['p'] : 1;
        $limit                   = $request->has('limit') ? $params['limit'] : 8;
        $status 		         = $request->has('status') ? $params['status'] : null;
        $keyword                 = $request->has('keyword') ? $params['keyword'] : null;
        $count                   = Db::name('repair')->count();
        

        if(empty($keyword)) {
                if(empty($status)) {
                        $posts          = Db::name('repair')->limit(($p - 1) * $limit, $limit)->select();
                } else {
                        $map['status']  = $status;
                        $posts          = Db::name('repair')->where($map)->limit(($p - 1) * $limit, $limit)->select();
                }
        } else {
                $map['name']            = array('like', '%'.$keyword.'%');
                $posts                  = Db::name('repair')->where($map)->limit(($p - 1) * $limit, $limit)->select();
        }

        

        foreach ($posts as $key => &$value) {
                $t_time          = $value['time'];
                $a_hour          = floor((($value['a_hour'] - $t_time) / 60) * 10) / 10;
                $c_hour          = floor((($value['c_hour'] - $t_time) / 60) * 10) / 10;



                $a_hour          = $a_hour >= 60 ? (floor(($a_hour / 60) * 10) / 10) . '时' : $a_hour .'分';
                $c_hour          = $c_hour >= 60 ? (floor(($c_hour / 60) * 10) / 10) . '时' : $c_hour .'分';

                $value['a_hour'] = $a_hour <= 0  ? '未受理' : $a_hour;
                $value['c_hour'] = $c_hour <= 0  ? '未完工' : $c_hour;

                $time            = explode(' ', date('Y-m-d H:i:s', $t_time));
                $value['time']   = $time[0];
                $value['date']   = $time[0];
                $value['times']  = $time[1];
                $value['uuname'] = $this->get_user_config($value['uid']);
        }

        if($posts) {
        	return $this->succ($posts);
        } else {
        	return $this->erro($posts);
        }
	}

        public function lists1() {
            // 这是获取当月月初和月末的时间戳
            $map1['time']  = array('BETWEEN',array(mktime(0,0,0,date('m'),1,date('Y')), mktime(23,59,59,date('m'),date('t'),date('Y'))));

            //php获取今日开始时间戳和结束时间戳
            $map2['time']  = array('BETWEEN',array(mktime(0,0,0,date('m'),date('d'),date('Y')), mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1));

            //php获取昨日起始时间戳和结束时间戳
            $map3['time']  = array('BETWEEN',array(mktime(0,0,0,date('m'),date('d')-1,date('Y')), mktime(0,0,0,date('m'),date('d'),date('Y'))-1));

            //php获取上周起始时间戳和结束时间戳
            $map4['time']  = array('BETWEEN',array(mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y')), mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'))));
            $arr           = ['昨日', '今日', '今周', '今月', '今年'];
            $array         = array();
            foreach($arr as $key   => &$value) {
                    switch ($key) {
                            case 0:
                            $map = $map3;
                            break;
                            case 1:
                            $map = $map2;
                            break;
                            case 2:
                            $map = $map4;
                            break;
                            case 3:
                            $map = $map1;
                            break;
                            case 4:
                            $map = array();
                            break;
                    }
                    $map['status']          = 0;
                    $arr1['shen']           = Db::name('repair')->where($map)->count();
                    $map['status']          = 1;
                    $arr1['shou']           = Db::name('repair')->where($map)->count();
                    $map['status']          = 2;
                    $arr1['wei']            = Db::name('repair')->where($map)->count();
                    $map['status']          = 3;
                    $arr1['weied']          = Db::name('repair')->where($map)->count();
                    $map['status']          = 4;
                    $arr1['ping']           = Db::name('repair')->where($map)->count();
                    $arr1['name']           = $value;
                    $arr1['all']            = $arr1['shen'] + $arr1['shou'] + $arr1['wei'] + $arr1['weied'] + $arr1['ping'];
                    $array[]                = $arr1;
                    $arr1                   = [];
            }
            if($array) {
                    return $this->succ($array);
            } else {
                    return $this->erro($array);
            }
        }

        public function export_excel(Request $request) {
                $data                   = $request->get();
                $model                  = $data['model'];

                if(empty($model)) return;
                
                $head_arr               = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS'];
                $res                    = Db::name($model)->find();
                
                if($request->has('arr')) {
                    $arr                        = $request->get()['arr'];
                    if($model == 'user') {
                            $map['uid']         = array('in', implode(',', $arr));
                        } else {
                            $map['id']          = array('in', implode(',', $arr));
                        }
                        $ress                   = Db::name($model)->where($map)->select();
                } else {
                        $ress                   = Db::name($model)->select();
                }

                $objPHPExcel            = new PHPExcel();
                $i                      = 0;
                $objPHPExcel->getProperties()->setCreator('http://www.phpernote.com')
                 ->setLastModifiedBy('http://www.phpernote.com')
                 ->setTitle('Office 2007 XLSX Document')
                 ->setSubject('Office 2007 XLSX Document')
                 ->setDescription('Document for Office 2007 XLSX, generated using PHP classes.')
                 ->setKeywords('office 2007 openxml php')
                 ->setCategory('Result file');


                $first_sheet       = $objPHPExcel->setActiveSheetIndex(0);
                $ii                     = 0;
                $i                      = 2;

                foreach($ress as $key => &$value) {
                        foreach($value as $k1 => &$v1) {
                                if($i == 2){
                                        $first_sheet->setCellValue($head_arr[$ii] . ($i - 1), $k1);
                                        $first_sheet->setCellValue($head_arr[$ii] . $i, $v1);
                                } else {
                                        $first_sheet->setCellValue($head_arr[$ii] . $i, $v1);
                                }
                                
                                $ii++;
                        }
                        $i++;
                        $ii = 0;
                }

                $objPHPExcel->getActiveSheet()->setTitle($model);
                $objPHPExcel->setActiveSheetIndex(0);

                $fileName = $model . '表';
                $xlsName  = iconv('utf-8', 'gb2312', $fileName);
            
                // !ajax
                // $objPHPExcel->getActiveSheet()->setTitle('sheet');
                // $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
                // ob_end_clean();     
                // header("Pragma: public");
                // header("Expires: 0");
                // header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
                // header("Content-Type:application/force-download");
                // header("Content-Type:application/vnd.ms-execl;charset=UTF-8");
                // header("Content-Type:application/octet-stream");
                // header("Content-Type:application/download");
                // header("Content-Disposition:attachment;filename=".$xlsName.".xls");
                // header("Content-Transfer-Encoding:binary");
                // $objWriter->save("php://output");

                // ajax
                $filename = $model.'表-'.date('YmdHis').'.xlsx';
                $objWriter= \PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel2007');
                $filePath = config('EXCEL_PATH').$filename;
                $objWriter->save($filePath);
                
                if(!file_exists($filename)) {
                    return $this->succ(array('url' => '/'.$filePath));
                } else {
                    return $this->erro();
                }   


                
        }

        public function get_user_config($uid, $field = 'username') {
                $map['uid']     = $uid;
                return Db::name('user')->where($map)->find()[$field];
        }
}
